<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>店铺管理</span>
      </div>
      <div class="filter-container">
        <el-input
          v-model="listQuery.shopName"
          placeholder="店铺名称"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-input
          v-model="listQuery.address"
          placeholder="店铺地址"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
          添加店铺
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="店铺名称" prop="name" align="center" min-width="120" />
        <el-table-column label="店铺简介" prop="service" align="center" min-width="150" />
        <el-table-column label="地址" align="center" min-width="200">
          <template #default="scope">
            {{ scope.row.fullAddress || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="联系方式" align="center" min-width="120">
          <template #default="scope">
            {{ scope.row.contact || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="店铺图片" align="center" prop="img" width="100">
          <template #default="scope">
            <div v-if="scope.row.imgUrl" class="image-container">
              <el-image
                style="width: 60px; height: 60px"
                :src="scope.row.imgUrl"
                fit="cover"
                :preview-src-list="[scope.row.imgUrl]"
                :initial-index="0"
              >
                <template #placeholder>
                  <div class="image-slot">
                    <el-icon><Loading /></el-icon>
                  </div>
                </template>
                <template #error>
                  <div class="image-slot">
                    <el-icon><PictureFilled /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.pageNum"
        :limit.sync="listQuery.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog 
      v-model="dialogFormVisible"
      :title="dialogTitle" 
      width="50%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
      >
        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入店铺名称"/>
        </el-form-item>
        
        <el-form-item label="店铺简介" prop="service">
          <el-input v-model="temp.service" placeholder="请输入店铺简介"/>
        </el-form-item>

        <el-form-item label="店铺地址" prop="fullAddress">
          <el-cascader
            v-model="addressSelected"
            :options="addressOptions"
            @change="handleAddressChange"
            placeholder="请选择省/市/区"
          />
          <el-input
            v-model="temp.detailAddress"
            placeholder="请输入详细地址"
            style="margin-top: 10px"
          />
        </el-form-item>

        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="temp.contact" placeholder="请输入联系方式"/>
        </el-form-item>

        <el-form-item label="店铺图片" prop="img">
          <el-upload
            class="avatar-uploader"
            :action="''"
            :show-file-list="false"
            :http-request="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="temp.img" :src="temp.img" class="avatar">
            <el-icon v-else><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/Pagination'
import { Search, Plus, Loading, PictureFilled } from '@element-plus/icons-vue'
import cloudbase from '@cloudbase/js-sdk'
import { regionData } from 'element-china-area-data'

export default {
  name: 'ShopView',
  components: { Pagination, Search, Plus, Loading, PictureFilled },
  setup() {
    const listLoading = ref(false)
    const list = ref([])
    const total = ref(0)
    const dialogFormVisible = ref(false)
    const dialogTitle = ref('')
    const selectedRows = ref([])
    const addressSelected = ref([])
    const addressOptions = ref(regionData)

    const listQuery = reactive({
      pageNum: 1,
      pageSize: 10,
      shopName: '',
      address: ''
    })

    const temp = reactive({
      name: '',
      service: '',
      fullAddress: '',
      detailAddress: '',
      contact: '',
      img: '', // 用于显示的临时URL
      fileID: '', // 保存原始或新上传的云存储fileID
      shop_id: '',
      originalImg: '',
      province: '',
      city: '',
      district: ''
    })

    const rules = {
      name: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
      service: [{ required: true, message: '请输入店铺简介', trigger: 'blur' }],
      detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
      contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
    }

    // 获取店铺列表
    const getList = async () => {
      listLoading.value = true
      try {
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()
        
        const res = await app.callFunction({
          name: 'Shop',
          data: { 
            action: 'query',
            pageNum: listQuery.pageNum,
            pageSize: listQuery.pageSize,
            shopName: listQuery.shopName,
            address: listQuery.address
          }
        })

        if (res.result && res.result.code === 200) {
          list.value = res.result.data
          total.value = res.result.total
        } else {
          ElMessage.error(res.result.message || '获取店铺列表失败')
        }
      } catch (error) {
        console.error('获取店铺列表失败:', error)
        ElMessage.error('获取店铺列表失败')
      } finally {
        listLoading.value = false
      }
    }

    // 处理地址选择变化
    const handleAddressChange = (value) => {
      if (value && value.length === 3) {
        const province = addressOptions.value.find(p => p.value === value[0])
        const city = province?.children?.find(c => c.value === value[1])
        const district = city?.children?.find(d => d.value === value[2])
        
        if (province && city && district) {
          // 保存分段地址
          temp.province = province.label
          temp.city = city.label
          temp.district = district.label
          // 拼接完整地址
          temp.fullAddress = `${province.label}${city.label}${district.label}${temp.detailAddress || ''}`
        }
      }
    }

    // 监听详细地址变化
    watch(() => temp.detailAddress, (newVal) => {
      if (addressSelected.value?.length === 3) {
        handleAddressChange(addressSelected.value)
      }
    })

    // 处理搜索
    const handleFilter = () => {
      listQuery.pageNum = 1
      getList()
    }

    // 处理选择变化
    const handleSelectionChange = (val) => {
      selectedRows.value = val
    }

    // 处理创建
    const handleCreate = () => {
      dialogTitle.value = '添加店铺'
      dialogFormVisible.value = true
      // 重置所有字段
      Object.assign(temp, {
        name: '',
        service: '',
        fullAddress: '',
        detailAddress: '',
        contact: '',
        img: '',
        fileID: '',
        shop_id: Date.now().toString(),
        _id: undefined,
        province: '',
        city: '',
        district: ''
      })
      addressSelected.value = []
    }

    // 处理更新
    const handleUpdate = async (row) => {
      dialogTitle.value = '编辑店铺'
      dialogFormVisible.value = true
      
      // 保存基础数据
      Object.assign(temp, {
        _id: row._id,
        name: row.name,
        service: row.service,
        fullAddress: row.fullAddress,
        province: row.province,
        city: row.city,
        district: row.district,
        detailAddress: row.detailAddress || '',
        contact: row.contact,
        shop_id: row.shop_id,
        fileID: row.fileID || row.img,
        img: row.imgUrl || ''
      })

      // 如果有省市区信息，设置地址选择器
      if (row.province && row.city && row.district) {
        // 查找对应的地址选项
        const findOption = (options, label) => {
          return options.find(opt => opt.label.includes(label))
        }

        const province = findOption(addressOptions.value, row.province)
        if (province) {
          const city = findOption(province.children || [], row.city)
          if (city) {
            const district = findOption(city.children || [], row.district)
            if (district) {
              addressSelected.value = [province.value, city.value, district.value]
            }
          }
        }
      }

      // 如果没有imgUrl但有fileID，获取临时URL
      if (!temp.img && temp.fileID) {
        try {
          const app = cloudbase.init({
            env: "cloud1-2gozbkkk09f11d05"
          })
          await app.auth().signInAnonymously()
          
          const urlResult = await app.callFunction({
            name: 'Shop',
            data: {
              action: 'getImageUrl',
              fileID: temp.fileID
            }
          })
          if (urlResult.result) {
            temp.img = urlResult.result
          }
        } catch (error) {
          console.error('获取图片URL失败:', error)
        }
      }
    }

    // 处理删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该店铺吗？', '提示', {
          type: 'warning'
        })
        
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()
        
        const res = await app.callFunction({
          name: 'Shop',
          data: { 
            action: 'delete',
            id: row._id
          }
        })

        if (res.result && res.result.code === 200) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error(res.result.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除店铺失败:', error)
          ElMessage.error('删除店铺失败')
        }
      }
    }

    // 处理批量删除
    const handleBatchDelete = async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的店铺')
        return
      }

      try {
        await ElMessageBox.confirm('确定要删除选中的店铺吗？', '提示', {
          type: 'warning'
        })
        
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()
        
        const res = await app.callFunction({
          name: 'Shop',
          data: { 
            action: 'batchDelete',
            ids: selectedRows.value.map(row => row._id)
          }
        })

        if (res.result && res.result.code === 200) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error(res.result.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除店铺失败:', error)
          ElMessage.error('批量删除店铺失败')
        }
      }
    }

    // 图片上传前的验证
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }

    // 处理图片上传
    const handleAvatarSuccess = async (options) => {
      try {
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()

        const file = options.file
        const fileType = file.type.split('/')[1]
        const fileName = `shop图片/${Date.now()}.${fileType}`

        // 转换为 base64
        const reader = new FileReader()
        const base64Promise = new Promise((resolve, reject) => {
          reader.onload = () => resolve(reader.result.split(',')[1])
          reader.onerror = error => reject(error)
          reader.readAsDataURL(file)
        })

        const base64Data = await base64Promise

        // 调用云函数上传图片
        const uploadResult = await app.callFunction({
          name: 'Shop',
          data: {
            action: 'uploadImage',
            file: {
              name: fileName,
              data: base64Data
            }
          }
        })

        if (uploadResult.result) {
          const newFileID = uploadResult.result
          // 获取临时访问链接
          const urlResult = await app.callFunction({
            name: 'Shop',
            data: {
              action: 'getImageUrl',
              fileID: newFileID
            }
          })

          if (urlResult.result) {
            // 只有在成功上传新图片时才更新fileID
            temp.fileID = newFileID // 新的云存储ID
            temp.img = urlResult.result // 显示用的临时URL
            ElMessage.success('上传成功')
          } else {
            throw new Error('获取图片预览链接失败')
          }
        } else {
          throw new Error('上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('上传失败: ' + (error.message || '未知错误'))
      }
    }

    // 提交表单
    const submitForm = async () => {
      try {
        const app = cloudbase.init({
          env: "cloud1-2gozbkkk09f11d05"
        })
        
        await app.auth().signInAnonymously()

        const data = {
          action: temp._id ? 'update' : 'add',
          name: temp.name,
          service: temp.service,
          fullAddress: temp.fullAddress,
          province: temp.province,
          city: temp.city,
          district: temp.district,
          detailAddress: temp.detailAddress,
          contact: temp.contact,
          shop_id: temp.shop_id,
          img: temp.fileID || ''
        }

        if (temp._id) {
          data._id = temp._id
        }

        // 确保所有必填字段都有值
        if (!data.name || !data.service || !data.fullAddress || !data.contact || !data.shop_id) {
          ElMessage.warning('请填写所有必填字段')
          return
        }

        const res = await app.callFunction({
          name: 'Shop',
          data
        })

        if (res.result && res.result.code === 200) {
          ElMessage.success(temp._id ? '更新成功' : '添加成功')
          dialogFormVisible.value = false
          getList()
        } else {
          ElMessage.error(res.result.message || (temp._id ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error('提交表单失败')
      }
    }

    onMounted(() => {
      getList()
    })

    return {
      listLoading,
      list,
      total,
      listQuery,
      dialogFormVisible,
      dialogTitle,
      temp,
      rules,
      addressSelected,
      addressOptions,
      handleFilter,
      handleSelectionChange,
      handleCreate,
      handleUpdate,
      handleDelete,
      handleBatchDelete,
      submitForm,
      handleAvatarSuccess,
      beforeAvatarUpload,
      handleAddressChange,
      getList
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.avatar-uploader {
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>